package qc.module.ehs.api.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import qc.common.core.constants.QCAuthConstant;
import qc.common.core.exception.QCPromptException;
import qc.module.ehs.dto.org.EhsOrgDto;
import qc.module.ehs.dto.unit.EhsUnitDto;
import qc.module.ehs.dto.unit.EhsUnitQueryConditionDto;
import qc.module.ehs.dto.unit.EhsUnitTreeSimpleDto;
import qc.module.ehs.dto.unit.EhsUnitTreeTableItemDto;
import qc.module.ehs.service.EhsOrgService;
import qc.module.ehs.service.EhsUnitBasicService;
import qc.module.platform.dto.dept.DeptSimpleDto;
import qc.module.platform.dto.uac.UacUserInfoDto;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * EhsUnitBasicController
 *
 * @author QuCheng Tech
 * @create 2024/5/22
 */
@RestController
@RequestMapping("/unit")
public class UnitController {
    
    @Autowired
    private EhsUnitBasicService service;

    @Autowired
    HttpServletRequest request;
    
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    
    @Autowired
    private EhsOrgService orgService;
    
    @Autowired
    private OrgController orgController;

    /**
     * 查询单元信息，以TreeTable树型形式返回数据
     * 条件组织编码根据token处理获取设置
     * 
     * @param condition 查询条件
     * @return List<EhsUnitTreeTableItemDto>
     * @author QuCheng Tech
     * @since 2024/5/30
     */
    @RequestMapping(value = "/treetable",method = {RequestMethod.GET,RequestMethod.POST})
    public List<EhsUnitTreeTableItemDto> queryTreeTable(@RequestBody EhsUnitQueryConditionDto condition) throws QCPromptException {
        //根据token获取用户所在项目中有效的部门集合
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        List<DeptSimpleDto> depts = getUserValidDepts(token);
        
        //获取部门ID集合，根据部门ID集合找出一个组织代码
        if (CollectionUtils.isEmpty(depts)) throw new QCPromptException("当前用户无有效项目部门信息");
        List<Integer> deptIds = depts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());
        //String orgCode = orgService.getOrgCodeByDeptIds(deptIds);
        //if (StringUtils.isBlank(orgCode)) throw new QCPromptException("当前用户无有效组织信息");
        //condition.setOrgcode(orgCode);
        UacUserInfoDto userInfo = getUserInfo(token);
        String projectCode = userInfo.getProject();
        EhsOrgDto org = orgController.getUserOrgByParam(projectCode);
        if (Objects.isNull(org)) throw new QCPromptException("当前用户无有效组织信息");
        condition.setOrgcode(org.getOrgcode());
        
        return service.queryTreeTable(condition,deptIds);
    }

    /**
     * 查询单元简要信息
     * 用于在其他模块（如危险源台账）作为查询条件或表单选择数据接口使用；以层级形式返回单元列表（可以根据条件根据用户部门筛选）
     * 
     * @param condition 查询条件
     * @return List<EhsUnitTreeSimpleDto>
     * @throws QCPromptException
     * @author QuCheng Tech
     * @since 2024/5/31
     */
    @RequestMapping(value = "/treesimple",method = {RequestMethod.GET,RequestMethod.POST})
    public List<EhsUnitTreeSimpleDto> queryTreeSimple(@RequestBody EhsUnitQueryConditionDto condition) throws QCPromptException {
        //根据token获取用户所在项目中有效的部门集合
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        List<DeptSimpleDto> depts = getUserValidDepts(token);

        //获取部门ID集合，根据部门ID集合找出一个组织代码
        if (CollectionUtils.isEmpty(depts)) throw new QCPromptException("当前用户无有效项目部门信息");
        List<Integer> deptIds = depts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());
        //String orgCode = orgService.getOrgCodeByDeptIds(deptIds);
        //if (StringUtils.isBlank(orgCode)) throw new QCPromptException("当前用户无有效组织信息");
        //condition.setOrgcode(orgCode);
        UacUserInfoDto userInfo = getUserInfo(token);
        String projectCode = userInfo.getProject();
        EhsOrgDto org = orgController.getUserOrgByParam(projectCode);
        if (Objects.isNull(org)) throw new QCPromptException("当前用户无有效组织信息");
        condition.setOrgcode(org.getOrgcode());
        
        return service.queryTreeSimple(condition,deptIds);
    }

    /**
     * 查询单元信息，以List形式返回数据 TODO 待定 未完成
     * 条件组织编码根据token处理获取设置
     *
     * @param condition 查询条件
     * @return List<EhsUnitTreeTableItemDto>
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public List<EhsUnitDto> queryList(@RequestBody EhsUnitQueryConditionDto condition) throws QCPromptException {
        //根据token获取用户所在项目中有效的部门集合
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        List<DeptSimpleDto> depts = getUserValidDepts(token);
        
        //获取部门ID集合，根据部门ID集合找出一个组织代码
        if (CollectionUtils.isEmpty(depts)) throw new QCPromptException("当前用户无有效项目部门信息");
        List<Integer> deptIds = depts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());
        //String orgCode = orgService.getOrgCodeByDeptIds(deptIds);
        //if (StringUtils.isBlank(orgCode)) throw new QCPromptException("当前用户无有效组织信息");
        //condition.setOrgcode(orgCode);
        UacUserInfoDto userInfo = getUserInfo(token);
        String projectCode = userInfo.getProject();
        EhsOrgDto org = orgController.getUserOrgByParam(projectCode);
        if (Objects.isNull(org)) throw new QCPromptException("当前用户无有效组织信息");
        condition.setOrgcode(org.getOrgcode());
        
        return service.queryList(condition,deptIds);
    }

    /**
     * 获取指定 - 同时支持@RequestParam和@PathVariable方式
     *
     * @param id 单元代码
     * @return EhsUnitDto
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @GetMapping("/get")
    public EhsUnitDto getByParam(@RequestParam String id) throws QCPromptException {
        return service.get(id);
    }

    /**
     * 获取指定 - 同时支持@RequestParam和@PathVariable方式
     *
     * @param id 单元代码
     * @return EhsUnitDto
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @GetMapping("/get/{id}")
    public EhsUnitDto getByPath(@PathVariable String id) throws QCPromptException {
        return service.get(id);
    }

    /**
     * 新增 
     * 
     * @param dto 单元信息
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @RequestMapping(value = "/add",method = {RequestMethod.GET,RequestMethod.POST})
    public String add(@RequestBody EhsUnitDto dto){
        return service.add(dto);
    }

    /**
     * 修改
     *
     * @param dto 单元信息
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.PUT})
    public String update(@RequestBody EhsUnitDto dto) {
        return service.update(dto);
    }

    /**
     * 删除 - 同时支持@RequestParam和@PathVariable方式
     *
     * @param id 单元编码
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    @DeleteMapping("/delete")
    public String deleteByParam(@RequestParam String id){
        return service.delete(id);
    }

    /**
     * 删除 - 同时支持@RequestParam和@PathVariable方式
     * 
     * @param id 单元编码
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    @DeleteMapping("/delete/{id}")
    public String deleteByPath(@PathVariable String id){
        return service.delete(id);
    }

    /**
     * 根据token获取用户所在项目中所有有效的部门
     *
     * @param token 用户登录得到的Token
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    //public List<DeptSimpleDto> getProjectValidDepts(String token) {
    //    HttpHeaders headers = new HttpHeaders();
    //    headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);
    //
    //    ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
    //    String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/projectvalid";
    //
    //    HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
    //    ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
    //    };
    //
    //    ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
    //            url,//获取资源的地址
    //            HttpMethod.GET,
    //            formEntity,
    //            responseType
    //    );
    //    List<DeptSimpleDto> resultDto = response.getBody();
    //    return resultDto;
    //}

    /**
     * 根据token获取用户有效的部门
     *
     * @param token 用户登录得到的Token
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2024/7/18
     */
    public List<DeptSimpleDto> getUserValidDepts(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/uservalid";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        List<DeptSimpleDto> resultDto = response.getBody();
        return resultDto;
    }

    /**
     * 根据token获取用户信息
     *
     * @param token 用户登录得到的Token
     * @return 用户
     * @author QuCheng Tech
     * @since 2024/7/1
     */
    public UacUserInfoDto getUserInfo(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/uac/userinfo";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<UacUserInfoDto> responseType = new ParameterizedTypeReference<UacUserInfoDto>() {
        };

        ResponseEntity<UacUserInfoDto> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        UacUserInfoDto resultDto = response.getBody();

        return resultDto;
    }
}
